<template>
  <div class="wms-item-search">
    <ElCard shadow="never" class="search-card">
      <ElForm
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <ElRow :gutter="16">
          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="商品编码" prop="itemCode">
              <ElInput
                v-model="searchForm.itemCode"
                placeholder="请输入商品编码"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="商品名称" prop="itemName">
              <ElInput
                v-model="searchForm.itemName"
                placeholder="请输入商品名称"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="商品分类" prop="categoryId">
              <ElTreeSelect
                v-model="searchForm.categoryId"
                :data="categoryTreeData"
                :props="{ label: 'categoryName', value: 'id' }"
                placeholder="请选择商品分类"
                clearable
                filterable
                check-strictly
                :render-after-expand="false"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="商品品牌" prop="brandId">
              <ElSelect
                v-model="searchForm.brandId"
                placeholder="请选择商品品牌"
                clearable
                filterable
                style="width: 100%"
              >
                <ElOption
                  v-for="brand in brandList"
                  :key="brand.id"
                  :label="brand.brandName"
                  :value="brand.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="计量单位" prop="unit">
              <ElInput
                v-model="searchForm.unit"
                placeholder="请输入计量单位"
                clearable
                @keyup.enter="handleSearch"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem label="创建时间" prop="createTimeRange">
              <ElDatePicker
                v-model="searchForm.createTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="6" :md="8" :sm="12" :xs="24">
            <ElFormItem>
              <ElSpace>
                <ElButton type="primary" @click="handleSearch" v-ripple>
                  <ElIcon><Search /></ElIcon>
                  搜索
                </ElButton>
                <ElButton @click="handleReset" v-ripple>
                  <ElIcon><Refresh /></ElIcon>
                  重置
                </ElButton>
                <ElButton
                  type="info"
                  text
                  @click="toggleExpand"
                  v-if="showExpandButton"
                >
                  <ElIcon
                    ><component :is="isExpanded ? ArrowUp : ArrowDown"
                  /></ElIcon>
                  {{ isExpanded ? "收起" : "展开" }}
                </ElButton>
              </ElSpace>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { useWmsStore } from "@/store/modules/wms";
import { Search, Refresh, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";

defineOptions({ name: "WmsItemSearch" });

// Props
interface Props {
  filter?: WMS.Item.QueryParams;
}

const props = withDefaults(defineProps<Props>(), {
  filter: () => ({}),
});

// Emits
interface Emits {
  (e: "search", params: WMS.Item.QueryParams): void;
  (e: "reset"): void;
  (e: "update:filter", params: WMS.Item.QueryParams): void;
}

const emit = defineEmits<Emits>();

// 状态管理
const wmsStore = useWmsStore();

// 表单引用
const searchFormRef = ref<FormInstance>();

// 搜索表单数据
const searchForm = ref<WMS.Item.QueryParams>({
  itemCode: "",
  itemName: "",
  categoryId: undefined,
  brandId: undefined,
  unit: "",
  createTimeRange: undefined,
});

// 展开/收起状态
const isExpanded = ref(false);
const showExpandButton = ref(true);

// 计算属性
const categoryTreeData = computed(() => {
  return wmsStore.itemCategoryTreeList || [];
});

const brandList = computed(() => {
  return wmsStore.getActiveItemBrands || [];
});

// 监听props变化
watch(
  () => props.filter,
  (newFilter) => {
    if (newFilter) {
      Object.assign(searchForm.value, newFilter);
    }
  },
  { immediate: true, deep: true },
);

// 监听搜索表单变化
watch(
  searchForm,
  (newForm) => {
    emit("update:filter", { ...newForm });
  },
  { deep: true },
);

// 搜索处理
const handleSearch = () => {
  const params = { ...searchForm.value };

  // 处理时间范围
  if (params.createTimeRange && params.createTimeRange.length === 2) {
    params.createTimeStart = params.createTimeRange[0];
    params.createTimeEnd = params.createTimeRange[1];
    delete params.createTimeRange;
  }

  // 过滤空值
  Object.keys(params).forEach((key) => {
    if (
      params[key] === "" ||
      params[key] === null ||
      params[key] === undefined
    ) {
      delete params[key];
    }
  });

  emit("search", params);
};

// 重置处理
const handleReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.value = {
    itemCode: "",
    itemName: "",
    categoryId: undefined,
    brandId: undefined,
    unit: "",
    createTimeRange: undefined,
  };
  emit("reset");
};

// 展开/收起切换
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

// 初始化
onMounted(() => {
  // 确保基础数据已加载
  if (wmsStore.itemCategoryTreeList.length === 0) {
    wmsStore.getItemCategoryTreeList();
  }
  if (wmsStore.itemBrandList.length === 0) {
    wmsStore.getItemBrandList();
  }
});

// 暴露方法
defineExpose({
  handleSearch,
  handleReset,
  searchForm,
});
</script>

<style lang="scss" scoped>
.wms-item-search {
  margin-bottom: 16px;

  .search-card {
    :deep(.el-card__body) {
      padding: 16px 20px;
    }
  }

  .search-form {
    :deep(.el-form-item) {
      margin-bottom: 16px;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
    }
  }
}

// 响应式处理
@media (max-width: 768px) {
  .wms-item-search {
    .search-form {
      :deep(.el-form-item) {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
